package UF_IN;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.URL;

public class Example_02 {
    public boolean checkMeta(InputStream stream) {
        byte[] b = new byte[8];
        try {
            final long l = stream.available();
            if (l < 8) {
                return false;
            }
            stream.read(b);
        } catch (IOException e) {
            return false;
        }

        // Cast unsigned character constants prior to comparison
        return (b[0] == (byte) 'm' && b[1] == (byte) 'y' &&
                b[2] == (byte) 'f' && b[3] == (byte) 'o' &&
                b[4] == (byte) 'r' && b[5] == (byte) 'm' &&
                b[6] == (byte) 'a' && b[7] == (byte) 't');
    }

    public void printOut(final URL url, final PrintStream ps) throws IOException {
        final InputStream stream = url.openStream();
        try {
            if (checkMeta(stream)) {
                try {
                    ps.println("content:");
                    byte[] b = new byte[1024];
                    int i;
                    while ((i = stream.read(b)) > 0) {
                        ps.print(new String(b, 0, i));
                    }
                    ps.println();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } finally {
            try {
                stream.close();
            } catch (IOException e) {
                // do nothing
            }
        }
    }
}
